package com.classicmodels.model;

import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;

public class CustomerDAO {
    

    public static Customer[] all() throws Exception{
         //select * from customers;
        // Devuelve un array con todos los Customers;
        Connection c = Datasource.getConnection();
        Statement s = c.createStatement();
        ResultSet result = s.executeQuery("select * from Customers");
        ArrayList<Customer> customers = new ArrayList<Customer>();
        while(result.next()){
        	Customer customer = new Customer();
        	customer.setCustomerName(result.getString("customerName"));
        	customer.setCustomerNumber(result.getInt("customerNumber"));
        	customer.setPhone(result.getString("phone"));
        	customer.setContactFirstName(result.getString("contactFirstName"));
        	customer.setContactLastName(result.getString("contactLastName"));
        	customer.setAddressLine1(result.getString("addressline1"));
        	customer.setAddressLine2(result.getString("addressline2"));
        	customer.setCity(result.getString("city"));
        	customer.setState(result.getString("state"));
        	customer.setPostalCode(result.getString("postalCode"));
        	customer.setCountry(result.getString("country"));
        	customer.setSalesRepEmployeeNumber(result.getInt("salesRepEmployeeNumber"));
        	customer.setCreditLimit(result.getInt("creditLimit"));
        	customers.add(customer);
        	
        	}
        Customer[] customersArray = new Customer[customers.size()];
        return customers.toArray(customersArray);
        //return (Customer[])customers.toArray();
    }

public static void save(Customer customer) throws Exception{
    Connection c = Datasource.getConnection();
    String cadenaSQL = "INSERT INTO Customers( customerName,customerNumber,phone,contactFirstName,contactLastName,addressline1,addressline2,city,state,postalCode,country,salesRepEmployeeNumber,creditLimit)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)";
    PreparedStatement stmt = c.prepareStatement(cadenaSQL);
    stmt.setString(1, customer.getCustomerName());
    stmt.setInt(2, customer.getCustomerNumber());
    stmt.setString(3, customer.getPhone());
    stmt.setString(4, customer.getContactFirstName());
    stmt.setString(5, customer.getContactLastName());
    stmt.setString(6, customer.getAddressLine1());
    stmt.setString(7, customer.getAddressLine2());
    stmt.setString(8, customer.getCity());
    stmt.setString(9, customer.getState());
    stmt.setString(10, customer.getPostalCode());
    stmt.setString(11, customer.getCountry());
    stmt.setInt(12, customer.getSalesRepEmployeeNumber());
    stmt.setInt(13, customer.getCreditLimit());
    stmt.executeUpdate();
    
}   




}
